package com.xssq.service;

import com.xssq.utils.webSocket.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket服务器
 *
 * @author xssq
 * @version 1.0.0
 * @date 2023/08/27 05:34:58
 * @saying 你可以不会但你必须得知道
 */
@Component
@ServerEndpoint("/webSocket/{id}")
@Slf4j
public class WebSocketServer {
    /**
     * WebSocket的Util服务
     */
    public static WebSocketService webSocketService;

    /**
     *
     */
    public static ConcurrentHashMap<String, Session> sessionMap;

    /**
     * 连接建立成功调用的方法
     *
     * @param session
     * @param id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        webSocketService.onOpen(sessionMap, session, id);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        webSocketService.onClose(sessionMap, session);
    }

    /**
     * 接收客户端消息
     *
     * @param session 会话
     * @param message 消息
     */
    @OnMessage
    public void onMessage(Session session, String message) {
        webSocketService.onMessage(sessionMap, session, message);
    }

    /**
     * 连接错误
     *
     * @param session 会话
     * @param error   错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        webSocketService.onError(sessionMap, session, error);
    }

}
